const  { login } = require('../controller/user')
const  { successModel, errorModel } = require('../model/resModel')


const handleUserRouter = (req, res) => {
  const method = req.method

  // 登录
  if (method === 'GET' && req.path === '/api/user/login') {
    const { username, password } = req.query
    const result = login(username, password)
    return result.then(loginResult => {
      if (loginResult.username) {
        // 设置session
        req.session.username = loginResult.username
        req.session.relname = loginResult.relname
        console.log('req.session: ', req.session)
        return new successModel(loginResult)
      } else {
        return new errorModel('登录失败')
      }
    })
  }

  // 登录验证测试
  if (method === 'GET' && req.path === '/api/user/login-test') {
    if (req.session.username) {
      return Promise.resolve(new successModel({
        session: req.session
      }))
    } else {
      return Promise.resolve(new errorModel('尚未登录'))
    }
  }
}

module.exports = handleUserRouter